package com.canon.push.service.impl;

import com.google.gson.Gson;
import com.canon.push.entity.MessageEntity;
import com.canon.push.service.IRabbitMqSerivce;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.Charset;

/**
 * @Author canon
 * @Date 2019/12/26
 * @Description rabbitmq服务
 **/
public class RabbitMqServiceImpl implements IRabbitMqSerivce {
    Logger log = LoggerFactory.getLogger(RabbitMqServiceImpl.class);

    /**
     * 发送消息
     *
     * @param channel    channel
     * @param exchange   交换机
     * @param routingKey 路由键
     * @param properties 属性
     * @param entity     实体
     */
    @Override
    public void send(Channel channel, String exchange, String routingKey, AMQP.BasicProperties properties, MessageEntity entity) throws RuntimeException {
        try {
            channel.basicPublish(exchange, routingKey, false, properties, new Gson().toJson(entity).getBytes(Charset.forName("UTF-8")));
        } catch (Exception e) {
            log.error("send mq message exception：{}", e.getMessage());
            e.printStackTrace();
            throw new RuntimeException("send mq message exception:" + e.getMessage());
        }

    }

    /**
     * 发送消息
     *
     * @param channel    channel
     * @param exchange   交换机
     * @param routingKey 路由键
     * @param entity     实体
     */
    @Override
    public void send(Channel channel, String exchange, String routingKey, MessageEntity entity) throws RuntimeException {
        AMQP.BasicProperties basicProperties = new AMQP.BasicProperties()
                .builder()
                .deliveryMode(2)
                .contentType("application/json")
                .contentEncoding("UTF-8")
                .build();
        this.send(channel, exchange, routingKey, basicProperties, entity);

    }
}
